﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;

namespace Douban.Core.Converters
{
    public class DateConverter : IValueConverter
    {
        public string Parse(DateTime dateTime)
        {
            if (dateTime == default(DateTime)) return "";

            DateTime now = DateTime.Now;
            TimeSpan timeSpan = now - dateTime;

            int passedSeconds = (int)timeSpan.TotalSeconds;
            if (passedSeconds < 0) passedSeconds = -passedSeconds;

            //In same day
            if (dateTime.DayOfYear == now.DayOfYear)
            {
                if (passedSeconds < 60)
                    return passedSeconds + "秒前";

                if (passedSeconds >= 60 && passedSeconds < 3600)
                    return passedSeconds / 60 + "分钟前";

                if (passedSeconds >= 3600 && passedSeconds < 3600 * 24)
                    return passedSeconds / 3600 + "小时前";
            }

            if (dateTime.Year == now.Year)
                return dateTime.ToString("MM-dd HH:mm:ss");

            return dateTime.ToString("yyyy-MM-dd HH:mm:ss");
        }

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null)
                return Parse((DateTime)value);

            return "";
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
